"""
移动端API服务
为Flutter移动端应用提供RESTful API接口
"""

import os
import json
from fastapi import FastAPI, HTTPException, Depends, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel
from datetime import datetime

# 导入现有的数据库配置和模型
from main import get_db_engine, SessionLocal, Product as ProductModel, TradeRecord as TradeRecordModel

# 创建移动端API应用
app = FastAPI(
    title="交易监控系统移动端API",
    description="为Flutter移动端应用提供数据接口",
    version="1.0.0"
)

# 配置CORS，允许移动端应用访问
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost", "http://127.0.0.1", "*"],  # 允许所有来源，生产环境应限制
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 数据库依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# Pydantic模型定义
class ProductBase(BaseModel):
    name: str
    exchange_code: str
    margin: float
    stoploss: float
    takeprofit: float
    limit_stoploss: Optional[float] = None
    mtp: Optional[str] = None
    dks: Optional[str] = None
    is_monitored: bool

class ProductCreate(ProductBase):
    pass

class ProductResponse(ProductBase):
    id: int
    add_time: datetime
    
    class Config:
        from_attributes = True

class TradeRecordBase(BaseModel):
    product_name: str
    direction: str
    offset: str
    volume: float
    price: float
    reason: Optional[str] = None
    timestamp: datetime

class TradeRecordResponse(TradeRecordBase):
    id: int
    created_at: datetime
    
    class Config:
        from_attributes = True

# API路由
@app.get("/")
async def root():
    return {"message": "交易监控系统移动端API服务运行中"}

# 品种管理API
@app.get("/api/products", response_model=List[ProductResponse])
async def get_products(
    db: Session = Depends(get_db),
    page: int = Query(1, ge=1),
    limit: int = Query(100, ge=1, le=200),  # 增加默认限制到100，最大200
    search: Optional[str] = None,
    is_monitored: Optional[bool] = None
):
    """获取品种列表"""
    query = db.query(ProductModel)
    
    if search:
        query = query.filter(ProductModel.name.contains(search))
    
    if is_monitored is not None:
        query = query.filter(ProductModel.is_monitored == is_monitored)
    
    # 分页
    offset = (page - 1) * limit
    products = query.offset(offset).limit(limit).all()
    
    return products

@app.get("/api/products/{product_id}", response_model=ProductResponse)
async def get_product(product_id: int, db: Session = Depends(get_db)):
    """获取单个品种详情"""
    product = db.query(ProductModel).filter(ProductModel.id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="品种不存在")
    return product

@app.post("/api/products", response_model=ProductResponse)
async def create_product(product: ProductCreate, db: Session = Depends(get_db)):
    """创建新品种"""
    # 检查是否已存在同名品种
    existing = db.query(ProductModel).filter(ProductModel.name == product.name).first()
    if existing:
        raise HTTPException(status_code=400, detail="品种名称已存在")
    
    db_product = ProductModel(
        name=product.name,
        exchange_code=product.exchange_code,
        margin=product.margin,
        stoploss=product.stoploss,
        takeprofit=product.takeprofit,
        limit_stoploss=product.limit_stoploss,
        mtp=product.mtp,
        dks=product.dks,
        is_monitored=product.is_monitored,
        add_time=datetime.now()
    )
    
    db.add(db_product)
    db.commit()
    db.refresh(db_product)
    
    return db_product

@app.put("/api/products/{product_id}", response_model=ProductResponse)
async def update_product(product_id: int, product: ProductCreate, db: Session = Depends(get_db)):
    """更新品种信息"""
    db_product = db.query(ProductModel).filter(ProductModel.id == product_id).first()
    if not db_product:
        raise HTTPException(status_code=404, detail="品种不存在")
    
    # 检查名称是否与其他品种冲突
    existing = db.query(ProductModel).filter(
        ProductModel.name == product.name,
        ProductModel.id != product_id
    ).first()
    if existing:
        raise HTTPException(status_code=400, detail="品种名称已存在")
    
    # 更新字段
    for field, value in product.dict().items():
        setattr(db_product, field, value)
    
    db.commit()
    db.refresh(db_product)
    
    return db_product

@app.delete("/api/products/{product_id}")
async def delete_product(product_id: int, db: Session = Depends(get_db)):
    """删除品种"""
    db_product = db.query(ProductModel).filter(ProductModel.id == product_id).first()
    if not db_product:
        raise HTTPException(status_code=404, detail="品种不存在")
    
    db.delete(db_product)
    db.commit()
    
    return {"message": "品种删除成功"}

# 交易记录API
@app.get("/api/trade-records", response_model=List[TradeRecordResponse])
async def get_trade_records(
    db: Session = Depends(get_db),
    page: int = Query(1, ge=1),
    limit: int = Query(20, ge=1, le=100),
    product_name: Optional[str] = None
):
    """获取交易记录列表"""
    query = db.query(TradeRecordModel)
    
    if product_name:
        query = query.filter(TradeRecordModel.product_name.contains(product_name))
    
    # 按时间倒序排列
    query = query.order_by(TradeRecordModel.timestamp.desc())
    
    # 分页
    offset = (page - 1) * limit
    records = query.offset(offset).limit(limit).all()
    
    return records

@app.get("/api/trade-records/{record_id}", response_model=TradeRecordResponse)
async def get_trade_record(record_id: int, db: Session = Depends(get_db)):
    """获取单个交易记录详情"""
    trade_record = db.query(TradeRecordModel).filter(TradeRecordModel.id == record_id).first()
    if not trade_record:
        raise HTTPException(status_code=404, detail="交易记录不存在")
    return trade_record

@app.post("/api/trade-records", response_model=TradeRecordResponse)
async def create_trade_record(trade_record: TradeRecordBase, db: Session = Depends(get_db)):
    """创建交易记录"""
    db_trade_record = TradeRecordModel(
        product_name=trade_record.product_name,
        direction=trade_record.direction,
        offset=trade_record.offset,
        volume=trade_record.volume,
        price=trade_record.price,
        reason=trade_record.reason,
        timestamp=trade_record.timestamp,
        created_at=datetime.now()
    )
    
    db.add(db_trade_record)
    db.commit()
    db.refresh(db_trade_record)
    
    return db_trade_record

@app.get("/api/statistics")
async def get_statistics(db: Session = Depends(get_db)):
    """获取系统统计信息"""
    # 品种统计
    total_products = db.query(ProductModel).count()
    monitored_products = db.query(ProductModel).filter(ProductModel.is_monitored == True).count()
    
    # 交易记录统计（今日）
    today = datetime.now().date()
    today_records = db.query(TradeRecordModel).filter(
        TradeRecordModel.timestamp >= datetime.combine(today, datetime.min.time())
    ).count()
    
    return {
        "total_products": total_products,
        "monitored_products": monitored_products,
        "today_trades": today_records,
        "system_status": "正常"
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8080)